<template>
	<view class="container" v-if="!listData.loading">
		<view class="main" v-if="listData.goods.length">
			<view class="nav">
				<view class="header">
					<view class="left" v-if="orderType == 'takein'">
						<view class="store-name">
							<text>{{ store.name }}</text>
							<view class="iconfont iconarrow-right"></view>
						</view>
						<view class="store-location">
							<!-- <image src='/static/images/imgs/location.png' style="width: 30rpx; height: 30rpx;" class="mr-10"></image> -->
							<text>距离您 {{ store.distance_text }}</text>
						</view>
					</view>
					<view class="left overflow-hidden" v-else>
						<view class="d-flex align-items-center overflow-hidden">
							<image src='/static/images/imgs/location.png' style="width: 30rpx; height: 30rpx;"
								class="mr-10"></image>
							<view class="font-size-extra-lg text-color-base font-weight-bold text-truncate">
								{{ address.street }}
							</view>
						</view>
						<view class="font-size-sm text-color-assist overflow-hidden text-truncate">
							由<text class="text-color-base" style="margin: 0 10rpx">{{ store.name }}</text>配送
						</view>
					</view>
					<view class="right">
						<view class="dinein" :class="{active: orderType == 'takein'}" @tap="setOrderType('takein')">
							<text>自取</text>
						</view>
						<view class="takeout" :class="{active: orderType == 'takeout'}" @tap="takout">
							<text>外卖</text>
						</view>
					</view>
				</view>
				<view class="coupon">
					<text class="title">加入门店会员群，领18元入群礼</text>
					<view class="iconfont iconarrow-right"></view>
				</view>
			</view>
			<view class="content">
				<scroll-view class="menus" :scroll-into-view="listData.menuScrollIntoView" scroll-with-animation
					scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.id}`"
							:class="{'current': item.id === listData.currentCateId}"
							v-for="(item, index) in listData.goods" :key="index" @tap="handleMenuTap(item.id)">
							<text>{{ item.name }}</text>
							<view class="dot" v-show="menuCartNum(item.id)">{{ menuCartNum(item.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<!-- goods list begin -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="listData.cateScrollTop"
					@scroll="handleGoodsScroll">
					<view class="wrapper">
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in listData.ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(item, index) in listData.goods" :key="index"
								:id="`cate-${item.id}`">
								<view class="title">
									<text>{{ item.name }}</text>
									<image :src="item.icon" class="icon"></image>
								</view>
								<view class="items">
									<!-- 商品 begin -->
									<view class="good" v-for="(good, key) in item.goods_list" :key="key">
										<image :src="good.images" class="image" @tap="showGoodDetailModal(item, good)">
										</image>
										<view class="right">
											<text class="name">{{ good.name }}</text>
											<text class="tips">{{ good.content }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.price }}</text>
												<view class="btn-group" v-if="good.use_property">
													<button type="primary" class="btn property_btn" hover-class="none"
														size="mini" @tap="showGoodDetailModal(item, good)">
														选规格
													</button>
													<view class="dot" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}
													</view>
												</view>
												<view class="btn-group" v-else>
													<button type="default" v-show="goodCartNum(good.id)" plain
														class="btn reduce_btn" size="mini" hover-class="none"
														@tap="handleReduceFromCart(item, good)">
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}
													</view>
													<button type="primary" class="btn add_btn" size="min"
														hover-class="none" @tap="handleAddToCart(item, good, 1)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
				<!-- goods list end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="listData.cart.length > 0">
				<view class="mark">
					<image src="/static/images/imgs/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}</view>
				<!-- <button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
					{{ disabledPay ? `差${spread}元起送` : '去结算' }}
				</button> -->
				<button type="primary" class="pay-btn" :disabled="disabledPay">
					{{ disabledPay ? `差${spread}元起送` : '选好了' }}
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- 商品详情模态框 begin -->
		<modal :show="listData.goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom
			padding="0rpx" radius="12rpx">
			<view class="cover">
				<image v-if="listData.good.images" :src="listData.good.images" class="image"></image>
				<view class="btn-group">
					<!-- <image src="/static/images/imgs/share-good.png"></image> -->
					<image src="/static/images/imgs/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ listData.good.name }}</view>
						<view class="tips">{{ listData.good.content }}</view>
					</view>
					<view class="properties" v-if="listData.good.use_property">
						<view class="property" v-for="(item, index) in listData.good.property" :key="index">
							<view class="title">
								<text class="name">{{ item.name }}</text>
								<view class="desc" v-if="item.desc">({{ item.desc }})</view>
							</view>
							<view class="values">
								<view class="value" v-for="(value, key) in item.values" :key="key"
									:class="{'default': value.is_default}" @tap="changePropertyDefault(index, key)">
									{{ value.value }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<view class="left">
					<view class="price">￥{{ listData.good.price }}</view>
					<view class="props" v-if="getGoodSelectedProps(listData.good)">
						{{ getGoodSelectedProps(listData.good) }}
					</view>
				</view>
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ listData.good.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont iconadd-select"></view>
					</button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->
		<!-- 购物车详情popup -->
		<car-detail direction="top" :show-pop="listData.cartPopupVisible" class="cart-popup">
			<template v-slot:content>
				<view class="top">
					<text @tap="handleCartClear">清空</text>
				</view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(item, index) in listData.cart" :key="index">
							<view class="left">
								<view class="name">{{ item.name }}</view>
								<view class="props">{{ item.props_text }}</view>
							</view>
							<view class="center">
								<text>￥{{ item.price }}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none"
									@tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none"
									@tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="orderType == 'takeout' && store.packing_fee">
							<view class="left">
								<view class="name">包装费</view>
							</view>
							<view class="center">
								<text>￥{{ parseFloat(store.packing_fee) }}</text>
							</view>
							<view class="right invisible">
								<button type="default" plain size="mini" class="btn" hover-class="none">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">1</view>
								<button type="primary" class="btn" size="min" hover-class="none">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</car-detail>
		<!-- 购物车详情popup -->
	</view>
	<view class="loading" v-else>
		<image src="/static/images/loading.gif"></image>
	</view>
</template>
<script setup>
	import modal from '@/components/modal/modal'
	import carDetail from '@/components/popup/carDetail'
	import {
		computed,
		reactive,
		nextTick,
		onMounted
	} from 'vue'
	import {
		carInfoStore
	} from '../../store/index.js'
	import {
		goodsData
	} from '../../api/goods.js'
	import {
		storeToRefs
	} from 'pinia'
	import swiper1 from '../../static/images/imgs/b1.jpeg'
	import swiper2 from '../../static/images/imgs/b2.jpeg'
	import swiper3 from '../../static/images/imgs/b3.jpeg'

	const mainStore = carInfoStore()
	const {
		orderType,
		address,
		store
	} = storeToRefs(mainStore)
	const listData = reactive({
		goods: [], //所有商品
		ads: [{
				image: swiper1
			},
			{
				image: swiper2
			},
			{
				image: swiper3
			}
		],
		loading: true,
		currentCateId: 6905, //默认分类
		cateScrollTop: 0,
		menuScrollIntoView: '',
		cart: [], //购物车
		goodDetailModalVisible: false, //是否饮品详情模态框
		good: {}, //当前饮品
		category: {}, //当前饮品所在分类
		cartPopupVisible: false,
		sizeCalcState: false
	})

	// 购物车计算
	const goodCartNum = computed(() => { //计算单个饮品添加到购物车的数量
		return (id) => listData.cart.reduce((acc, cur) => {
			if (cur.id === id) {
				return acc += cur.number
			}
			return acc
		}, 0)
	})
	const menuCartNum = computed(() => {
		return (id) => listData.cart.reduce((acc, cur) => {
			if (cur.cate_id === id) {
				return acc += cur.number
			}
			return acc
		}, 0)
	})
	const getCartGoodsNumber = computed(() => { // 计算购物车总数
		return listData.cart.reduce((acc, cur) => acc + cur.number, 0)
	})
	const getCartGoodsPrice = computed(() => { // 计算购物车总价
		return listData.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
	})
	const disabledPay = computed(() => { // 是否达到起送价
		return orderType == 'takeout' && (getCartGoodsPrice < store.min_price) ? true : false
	})
	const spread = computed(() => { // 差多少元起送
		if (orderType != 'takeout') return
		return parseFloat((store.min_price - getCartGoodsPrice).toFixed(2))
	})
	
	// 执行方法
	// 初始化
	const init = async () => {
		listData.loading = true
		await mainStore.getStore()
		listData.goods = goodsData
		listData.loading = false
		listData.cart = uni.getStorageSync('cart') || []
	}
	// 自取
	const setOrderType = (item)=>{
		mainStore.getOrderType(item)
	}
	// 外卖
	const takout = () => {
		if (orderType == 'takeout') return
		if (!mainStore.isLogin) {
			// uni.navigateTo({url: '/pages/login/login'})
			return
		}
		// uni.navigateTo({
		// 	url: ''
		// })
	}
	// 点击菜单事项
	const handleMenuTap = (id) => {
		if (!listData.sizeCalcState) {
			calcSize()
		}

		listData.currentCateId = id
		nextTick(() => {
			listData.cateScrollTop = listData.goods.find(item => item.id == id).top
		});
	}
	//商品列表滚动事件
	const handleGoodsScroll = ({detail}) => {
		if (!listData.sizeCalcState) {
			calcSize()
		}
		const { scrollTop } = detail
		let tabs = listData.goods.filter(item => item.top <= scrollTop).reverse()
		if (tabs.length > 0) {
			listData.currentCateId = tabs[0].id
		}
	}

	// calcSize
	const calcSize = () => {
		let h = 10
		let view = uni.createSelectorQuery().select('#ads')
		view.fields({
			size: true
		}, data => {
			h += Math.floor(data.height)
		}).exec()

		listData.goods.forEach(item => {
			let view = uni.createSelectorQuery().select(`#cate-${item.id}`)
			view.fields({
				size: true
			}, data => {
				item.top = h
				h += data.height
				item.bottom = h
			}).exec()
		})
		listData.sizeCalcState = true
	}
	// 添加到购物车
	const handleAddToCart = (cate, good, num) => {
		const index = listData.cart.findIndex(item => {
			if (good.use_property) {
				return (item.id === good.id) && (item.props_text === good.props_text)
			} else {
				return item.id === good.id
			}
		})
		if (index > -1) {
			listData.cart[index].number += num
		} else {
			listData.cart.push({
				id: good.id,
				cate_id: cate.id,
				name: good.name,
				price: good.price,
				number: num,
				image: good.images,
				use_property: good.use_property,
				props_text: good.props_text,
				props: good.props
			})
		}
	}
	// 
	const handleReduceFromCart = (item, good) => {
		const index = listData.cart.findIndex(item => item.id === good.id)
		listData.cart[index].number -= 1
		if (listData.cart[index].number <= 0) {
			listData.cart.splice(index, 1)
		}
	}
	// 打开详情模态框
	const showGoodDetailModal = (item, good) => {
		listData.good = JSON.parse(JSON.stringify({
			...good,
			number: 1
		}))
		listData.category = JSON.parse(JSON.stringify(item))
		listData.goodDetailModalVisible = true
	}
	// 关闭饮品详情模态框
	const closeGoodDetailModal = () => {
		listData.goodDetailModalVisible = false
		listData.category = {}
		listData.good = {}
	}
	// 改变默认属性值
	const changePropertyDefault = (index, key) => {
		listData.good.property[index].values.forEach(value => value.is_default = 0)
		listData.good.property[index].values[key].is_default = 1
		listData.good.number = 1
	}
	// 计算当前饮品所选属性
	const getGoodSelectedProps = (good, type = 'text') => {
		if (good.use_property) {
			let props = []
			good.property.forEach(({
				values
			}) => {
				values.forEach(value => {
					if (value.is_default) {
						props.push(type === 'text' ? value.value : value.id)
					}
				})
			})
			return type === 'text' ? props.join('，') : props
		}
		return ''
	}
	// 
	const handlePropertyAdd = () => {
		listData.good.number += 1
	}
	const handlePropertyReduce = () => {
		if (listData.good.number === 1) return
		listData.good.number -= 1
	}
	const handleAddToCartInModal = () => {
		const product = Object.assign({}, listData.good, {
			props_text: getGoodSelectedProps(listData.good),
			props: getGoodSelectedProps(listData.good, 'id')
		})
		handleAddToCart(listData.category, product, listData.good.number)
		closeGoodDetailModal()
	}
	// 打开/关闭购物车列表popup
	const openCartPopup = () => {
		listData.cartPopupVisible = !listData.cartPopupVisible
	}
	// 清空购物车
	const handleCartClear = () => {
		uni.showModal({
			title: '提示',
			content: '确定清空购物车么',
			success: ({
				confirm
			}) => {
				if (confirm) {
					listData.cartPopupVisible = false
					listData.cart = []
				}
			}
		})
	}
	const handleCartItemAdd = (index) => {
		listData.cart[index].number += 1
	}
	const handleCartItemReduce = (index) => {
		if (listData.cart[index].number === 1) {
			listData.cart.splice(index, 1)
		} else {
			listData.cart[index].number -= 1
		}
		if (!listData.cart.length) {
			listData.cartPopupVisible = false
		}
	}
	// const toPay =()=> {
	// 	if(!mainStore.isLogin) {
	// 		alert('login')
	// 		// uni.navigateTo({url: '/pages/login/login'})
	// 		return
	// 	}

	// 	uni.showLoading({title: '加载中'})
	// 	uni.setStorageSync('cart', JSON.parse(JSON.stringify(this.cart)))

	// 	uni.navigateTo({
	// 		alert('pay')
	// 		// url: '/pages/pay/pay'
	// 	})
	// 	uni.hideLoading()
	// }
	onMounted(() => {
		init()
	})
</script>

<style lang="scss" scoped>
	@import '~@/pages/menu/menu.scss';
</style>